#include "stdafx.h"

#include "StickyTweetsAppXP.h"

#include "LoginDialog.h"

CString loginScreenName;

INT_PTR CALLBACK LoginDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);

	switch (message)
	{
	case WM_INITDIALOG:
    SetDlgItemText(hDlg, IDC_TXT_SCREENNAME, StickyTweetsAppXP::GetInstance().GetSettings().ScreenName);
		return (INT_PTR)TRUE;

	case WM_COMMAND:
    switch (LOWORD(wParam))
    {
    case IDOK:
      return CmdOk_Command(hDlg);

    case IDCANCEL:
      EndDialog(hDlg, (INT_PTR)StatusStNoLogin);
      return (INT_PTR)TRUE;
    }
    break;

  case WM_CTLCOLORDLG:
    LOGBRUSH lb;
    static HBRUSH hBrush;

    lb.lbColor = RGB(154, 228, 232);
    lb.lbStyle = 0;

    hBrush = CreateBrushIndirect(&lb);
    return (INT_PTR)hBrush;

	case WM_PAINT:
  	PAINTSTRUCT ps;
		HDC hdc = BeginPaint(hDlg, &ps);

    // Draw labels
    SetBkColor(hdc, RGB(154, 228, 232));
    ExtTextOut(hdc, 12, 78, 0, NULL, L"user name or email address", 26, NULL);
    ExtTextOut(hdc, 12, 129, 0, NULL, L"password", 8, NULL);
    ExtTextOut(hdc, 32, 196, 0, NULL, L"remember me", 11, NULL);

    EndPaint(hDlg, &ps);
		break;
	}

	return (INT_PTR)FALSE;
}

INT_PTR CmdOk_Command(HWND hDlg)
{
  StickyTweetsStatus error = StatusStOk;

  StickyTweetsAppXP& app = StickyTweetsAppXP::GetInstance();

  loginScreenName = L"";

  TCHAR screenName[MaxLoadString];
  SecureZeroMemory(screenName, MaxLoadString);

  TCHAR password[MaxLoadString];
  SecureZeroMemory(password, MaxLoadString);

  GetDlgItemText(hDlg, IDC_TXT_SCREENNAME, screenName, MaxLoadString);
  GetDlgItemText(hDlg, IDC_TXT_PASSWORD, password, MaxLoadString);

  error = app.VerifyCredentials(screenName, password);

  if (error == StatusStOk)
  {
    loginScreenName = screenName;

    Settings settings = app.GetSettings();
    settings.ScreenName = screenName;
    settings.Password = password;
    settings.RememberMe = (IsDlgButtonChecked(hDlg, IDC_CHK_REMEMBERME) == BST_CHECKED ? TRUE : FALSE);
    error = app.SaveSettings(settings);
  }

  if (error == StatusStOk)
  {
    EndDialog(hDlg, StatusStOk);
  }
  else
  {
    TCHAR buffer[MaxErrorBuffer] = {'\0'};
    LoadString((HINSTANCE)GetWindowLongPtr(hDlg, GWLP_HINSTANCE), IDS_ERROR_ST_UNKNOWN, buffer, MaxLoadString);
    MessageBox(hDlg, buffer, L"StickyTweets", MB_OK);
    //DisplayError(hDlg, error);
  }

  return (INT_PTR)TRUE;
}